package com.cos.service.impl;

import com.cos.vo.Goods;
import com.cos.service.GoodsService;
import com.cos.utils.JsonUtils;
import com.cos.vo.SearchGoodsParam;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class GoodsServiceImpl implements GoodsService {
    @Autowired
    private RestHighLevelClient client;
    private String indexName="goods-index";
    private String typeName="goods-type";
    @Override
    public void addGoods(Goods goodsEntity) throws IOException {
        //创建一个添加请求
        IndexRequest indexRequest = new IndexRequest(indexName,typeName);
        //添加条件
        indexRequest.source(JsonUtils.toJson(goodsEntity), XContentType.JSON);
        //添加操作
        client.index(indexRequest, RequestOptions.DEFAULT);

    }

    @Override
    public List<Goods> search(SearchGoodsParam searchGoodsParam) throws IOException, InvocationTargetException, IllegalAccessException {

        List<Goods> list=new ArrayList<>();
        //创建查询请求
        SearchRequest request=new SearchRequest();
        //设置索引和类型
        request.indices(indexName).types(typeName);
        //查询条件
        SearchSourceBuilder builder = SearchSourceBuilder.searchSource();
        if(!StringUtils.isEmpty(searchGoodsParam.getKeyWord())){
            request.source(builder.query(QueryBuilders.multiMatchQuery(searchGoodsParam.getKeyWord(),"gname","gdesc")));
        }

        if (searchGoodsParam.getType()!=null){
              request.source(builder.query(QueryBuilders.termQuery("gtypeCid",searchGoodsParam.getType())));
        }
        //查询es
        SearchResponse search = client.search(request, RequestOptions.DEFAULT);
        SearchHit[] hits = search.getHits().getHits();
        Goods goods =null;
        for (SearchHit hit : hits) {
            //获取一条json数据
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            goods= new Goods();
            BeanUtils.populate(goods,sourceAsMap);
            list.add(goods);
        }
        System.out.println(list);
        return list;
    }


}
